#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 11 juin 2011

@author: nathanael
'''

from enthought.traits.api \
    import (HasTraits, File, Unicode, Instance, Any, Property, Button, List,
            Bool,
            cached_property, on_trait_change)
from enthought.traits.ui.api \
    import (View, VGroup, HGroup, Item, Group)
from enthought.traits.ui.menu \
    import (OKButton, CancelButton)

import os
import time


from pybible.data import DATA_PATH
from pybible.core.data import openBook
from pybible.core.find import FindKernel, RegexPattern
from pybible.core.regex import CustomWordPattern, RegexPatter

from pybible.ui.result import UIResultsI, UIResults_HTML_factory, UIResults_text_factory, UIResults_text_factory2


def find():
    book = openBook(os.path.join(DATA_PATH, 'french_jn_darby.xml'))
    obj = Find(data=book.get_part()._data,
               lingual=book.get_header().get_lingual(),
               kernel=FindKernel(results_factory=UIResults_HTML_factory()),
               pattern_factory=RegexPattern)
    return obj
    
class Find(HasTraits):
    data = Any
    
    str_pattern = Unicode
    
    lingual = Any
    case = Bool
    emphasis = Bool
    regex = Bool
    whole_word = Bool
    
    kernel = Any
    pattern_factory = Any
    pattern = Property(depends_on=('str_pattern', 'pattern_factory',
                                   'case', 'emphasis', 'regex', 'whole_word'))
    
    #results = Property(List, depends_on=('go'))
    results = Property(Instance(UIResultsI), depends_on=('go'))
    
    go = Button('Find')
    clear = Button('Clear')
    
    has_results = Property(Bool)
    is_valid = Property(Bool)
    has_case = Property(Bool)
    has_emphasis = Property(Bool)
    
    view = View(
            Group(
             HGroup(
              VGroup(
               Item('str_pattern',
                    label="Find",
                    show_label=False),
               Group(
                Item('case',
                     label="Case sensitive",
                     visible_when='has_case'),
                Item('emphasis',
                     label="With emphasis",
                     visible_when='has_emphasis'),
                Item('whole_word',
                     label="Whole word"),
                Item('regex',
                     label="Regular expressions"),
                label='Options',
                show_border=True
               ),
               HGroup(
                Item('clear', show_label=False, enabled_when='has_results'),
                Item('go', show_label=False, enabled_when='is_valid'),
               ),
              ),
              Group(
               Item('results',
                    show_label=False,
                    resizable=True,
                    style="custom"),
               label="Results",
               show_border=True,
               visible_when='has_results',
              ),
              label='Find',
              show_border=True),
             ),
            resizable=True,
           )

    @cached_property
    def _get_pattern(self):
        # build regex pattern
        s = self.str_pattern
        if self.regex:
            builder = RegexPattern
        else:
            if self.emphasis:
                e = self.lingual.get_emphasis()
            else:
                e = []
            builder = CustomWordPattern(whole_word=self.whole_word,
                                        case_sensitive=not self.case,
                                        emphasis_characters=e)
            
        return self.pattern_factory(builder.build_regex(s))
        
    @on_trait_change('pattern')
    def _update_kernel(self):
        self.kernel._pattern = self.pattern

    def _get_results(self):
        return self.kernel.get_results()
        #return UIResults(self.kernel.get_results())
        #return [r._get_html() 
        #        for r in self.kernel.get_result()]
    
    def _get_is_valid(self):
        return len(self.str_pattern) > 0
    
    def _get_has_results(self):
        return len(self.kernel.get_results().values) > 0

    def _get_has_case(self):
        return self.lingual.has_case()

    def _get_has_emphasis(self):
        return self.lingual.has_emphasis()

    def _clear_changed(self):
        self.kernel.clear()
        self.str_pattern = ""
        
    def _go_changed(self):
        self.kernel.clear()
        self.kernel._factory.reinit(booksname=self.lingual.get_books_name(short=True),
                                   data=self.data)
        if self.str_pattern:
            t = time.time()
            self.kernel.find(self.data)#, wait=True)
            print "found in %f" % (time.time() - t)

def main():
    return find()

if __name__ == '__main__':
    main().configure_traits()
